package edu.mse.camel.client.posterboard.ui.emflistener;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;

import com.cea.papyrus.core.editor.ModelManager;

import edu.mse.camel.client.posterboard.ui.editor.CamelModelUpdateSerialNumber;
import edu.mse.camel.client.posterboard.ui.editor.PosterBoardModelManager;

public class DiagramListener implements PropertyChangeListener, Adapter {
	
	private ModelManager papyrusModelManager;
	private PosterBoardModelManager pbModelManager;
	private CamelChangeRecorder2 recorder;
	private Notifier target;
	private CamelModelUpdateSerialNumber serialNumber;
	
	public DiagramListener(PosterBoardModelManager pbModelManager, CamelModelUpdateSerialNumber serialNumber) {
		this.pbModelManager = pbModelManager;
		this.papyrusModelManager = pbModelManager.getPapyrusModelManager();
		papyrusModelManager.getModelManagerListener().addPropertyChangeListener(this);
		this.serialNumber = serialNumber;
	}

	@Override
	public void propertyChange(PropertyChangeEvent arg0) {
		String prop = arg0.getPropertyName();
		if (ModelManager.DIAGRAM_ABOUT_TO_ADD.equals(prop)) {
			recorder = new CamelChangeRecorder2(pbModelManager.getResourceSet());
			recorder.beginRecording();
		} else if (ModelManager.CHILD_ADDED_PROP.equals(prop)) {
			if(recorder != null) {
				if(recorder.IsRecording()) {
					recorder.publish(serialNumber.getSerialNumberAndThenInc(), "outline change");
					recorder.dispose();
				}
			}
		}
	}	
	
	public void dispose() {
		papyrusModelManager.getModelManagerListener().removePropertyChangeListener(this);
		papyrusModelManager = null;
	}

	@Override
	public Notifier getTarget() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isAdapterForType(Object type) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void notifyChanged(Notification notification) {
		switch (notification.getEventType()) {
			case Notification.ADD:
				papyrusModelManager.getModelTreeEditPart().refresh();
				break;
			case Notification.REMOVE:
				papyrusModelManager.getModelTreeEditPart().refresh();
				break;
		}
		
	}

	@Override
	public void setTarget(Notifier newTarget) {
		this.target = newTarget;
		
	}
	
}
